//
//  WXSModifyViewController.m
//  SleepBooks
//
//  Created by rimi on 16/9/20.
//  Copyright © 2016年 rimi. All rights reserved.
//

#import "WXSModifyViewController.h"
#import "WXSLoginViewController.h"

@interface WXSModifyViewController ()<UITextFieldDelegate>

@property (strong, nonatomic) UITextField *userName;
@property (strong, nonatomic) UITextField *password;

@end

@implementation WXSModifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSubviews];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

// set subviews
- (void)setupSubviews{
    self.title = @"修改";
    [self setupBackBarButton];
    
    UIImageView *bgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg"]];
    [bgView setFrame:CGRectMake(0, 0, kBaseWidth, kBaesHeight)];
    [self.view addSubview:bgView];
    
    self.userName.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.password.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.navigationController.navigationBar.translucent = YES;
    
    self.userName.keyboardType = UIKeyboardTypeDefault;
    self.userName.returnKeyType = UIReturnKeyNext;
    [self.userName becomeFirstResponder];
    
    self.password.keyboardType = UIKeyboardTypeDefault;
    self.password.returnKeyType = UIReturnKeyDone;
    
    self.password.delegate = self;
    self.userName.delegate = self;
    
    UILabel *userName = [[UILabel alloc]initWithFrame:CGRectMake(20, 120, 60, 30)];
    UILabel *password = [[UILabel alloc]initWithFrame:CGRectMake(20, 180, 60, 30)];
    
    userName.text = @"账号";
    password.text = @"密码";
    
    userName.textColor = [UIColor whiteColor];
    password.textColor = [UIColor whiteColor];
    
    userName.font = [UIFont systemFontOfSize:16];
    password.font = [UIFont systemFontOfSize:16];
    
    [self.view addSubview:userName];
    [self.view addSubview:password];
    
    [self.view addSubview:self.userName];
    [self.view addSubview:self.password];

    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake(20, 300, kBaseWidth-40, 40);
    loginBtn.backgroundColor = [UIColor colorWithRed:1.000 green:0.333 blue:0.364 alpha:1.000];
    loginBtn.layer.cornerRadius = 5;
    loginBtn.layer.masksToBounds = YES;
    [loginBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(exit) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:loginBtn];
    
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    if (textField == self.userName && textField.text.length > 6) {
        [self showSheetAlert];
        return NO;
    }else if (textField == self.userName && textField.text.length == 0){
        [self showalert];
    }
    
    if (textField == self.password && textField.text.length < 6){
        [self showsheetAlert];
        return NO;
    }else if (textField == self.password && textField.text.length > 12){
        [self showAlert];
        return NO;
    }
    
    if (textField == self.userName) {
        //注销响应者
        [self.userName resignFirstResponder];
        [self.password becomeFirstResponder];
    }
    
    if (textField == self.password) {
        [self.password resignFirstResponder];
        [self.view endEditing:YES];
    }
    
    return YES;

}

//限制输入
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField == self.userName) {
        if (string.length) {
            NSString *regex = @"[a-zA-Z0-9\u4e00-\u9fa5]+";
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
            
            return [pred evaluateWithObject: string];
        }
        return true;
    }else{
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALLSTRING] invertedSet];
        
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        
        return [string isEqualToString:filtered];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES]; //实现该方法是需要注意view需要是继承UIControl而来的
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [self setupRightBarButtonWithTitle:@"保存" action:@selector(saveModifyWithName)];
}

#pragma mark - Button Action

- (void)saveModifyWithName{
    //判断空值、提示信息
    if (self.userName.text.length > 6){
        AlertViewController *alert = [[AlertViewController alloc]initWithTitle:@"账号不能超过6个字符！"];
        [self presentViewController:alert animated:YES completion:nil];
    }else if (self.password.text.length < 6){
        AlertViewController *alert = [[AlertViewController alloc]initWithTitle:@"密码必须大于6位数！"];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        AVQuery *query = [AVQuery queryWithClassName:@"UserInfo"];
        __block BOOL nameIsUsed = NO;
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            NSArray<AVObject *> *userInfo = objects;
            NSLog(@"aa=%@",userInfo);
            
            //遍历，判断重复
            for (int i = 0; i < userInfo.count ; i ++) {
                AVObject *dic = [userInfo objectAtIndex:i];
                
                NSLog(@"tt%@",dic);
            
                if ([dic[@"username"] isEqualToString:[NSString stringWithFormat:@"%@",self.userName.text]]) {
                    nameIsUsed = YES;
                    break;
                }else if (self.userName.text.length == 0){
                    nameIsUsed = NO;
                }
            }
            
            if (nameIsUsed) {
                AlertViewController *alert = [[AlertViewController alloc]initWithTitle:@"账号已被注册！"];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                [query whereKey:@"username" equalTo:self.name];
                [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                    NSArray<AVObject *> *userInfo1 = objects;
                    NSLog(@"cc%@",userInfo1);
                        
                    AVObject *todo =[AVObject objectWithClassName:@"UserInfo" objectId:userInfo1.firstObject.objectId];
                    // 如果用户没有输入账户名，则维持原来的账户名
                    if (self.userName.text.length == 0) {
                        self.userName.text = self.name;
                    }
                    // 如果用户只修改账户名，不修改密码
                    if (self.password.text.length == 0 && self.userName.text.length > 0) {
                        [todo setObject:self.userName.text forKey:@"password"];
                    }
                    // 如果用户只修改密码，不修改账户名
                    if (self.userName.text.length == 0 && self.password.text.length > 0) {
                        [todo setObject:self.password.text forKey:@"password"];
                    }
                  
                    // 修改属性
                    [todo setObject:self.userName.text forKey:@"username"];
                    [todo setObject:self.password.text forKey:@"password"];
                    // 保存到云端
                    [todo saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            [self showPromptWithMessage:@"修改成功！"];
                            NSLog(@"successed!");
                            if (self.passNameBlock != nil) {
                                self.passNameBlock(self.userName.text);
                            }
                            [self.navigationController popViewControllerAnimated:YES];
                        }else{
                            NSLog(@"error occured! %@",error.localizedDescription);
                            AlertViewController *alert = [[AlertViewController alloc]initWithTitle:@"账号修改失败"];
                            [self presentViewController:alert animated:YES completion:nil];
                        }
                    }];
                }];
            }
        }];
    }
}

- (void)exit{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"ExitStatu" object:nil];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - pvivate method

- (void)showsheetAlert{
    //创建弹出框 如果是Sheet类型不能添加textField
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"密码必须大于5位数" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //当点取消按钮时执行block里面方法
        NSLog(@"点击了确定按钮");
        [self dismissViewControllerAnimated:YES completion:nil];
        self.password.text = nil;
    }];
    //添加确定按钮
    [alertController addAction:sureAction];
    //因为alert是一个控制器，所以需要用控制器的跳转方式弹出
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)showSheetAlert{
    //创建弹出框 如果是Sheet类型不能添加textField
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"最多不能超过6个字符！" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //当点取消按钮时执行block里面方法
        NSLog(@"点击了确定按钮");
        [self dismissViewControllerAnimated:YES completion:nil];
        self.userName.text = nil;
    }];
    //添加确定按钮
    [alertController addAction:sureAction];
    //因为alert是一个控制器，所以需要用控制器的跳转方式弹出
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)showAlert{
    //创建弹出框 如果是Sheet类型不能添加textField
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"最多不能超过12个字符！" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //当点取消按钮时执行block里面方法
        NSLog(@"点击了确定按钮");
        [self dismissViewControllerAnimated:YES completion:nil];
        self.password.text = nil;
    }];
    //添加确定按钮
    [alertController addAction:sureAction];
    //因为alert是一个控制器，所以需要用控制器的跳转方式弹出
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)showalert{
    //创建弹出框 如果是Sheet类型不能添加textField
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"账号不能为空！" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //当点取消按钮时执行block里面方法
        NSLog(@"点击了确定按钮");
        [self dismissViewControllerAnimated:YES completion:nil];
        self.userName.text = nil;
    }];
    //添加确定按钮
    [alertController addAction:sureAction];
    //因为alert是一个控制器，所以需要用控制器的跳转方式弹出
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)alert{
    //创建弹出框 如果是Sheet类型不能添加textField
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"不能使用特殊字符！" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //当点取消按钮时执行block里面方法
        NSLog(@"点击了确定按钮");
        [self dismissViewControllerAnimated:YES completion:nil];
        self.userName.text = nil;
    }];
    //添加确定按钮
    [alertController addAction:sureAction];
    //因为alert是一个控制器，所以需要用控制器的跳转方式弹出
    [self presentViewController:alertController animated:YES completion:nil];
}

//block
- (void)passName:(PassNameBlock)block{
    self.passNameBlock = block;
}

#pragma mark - Lazy Load

- (UITextField *)userName{
    if (!_userName) {
        _userName = [[UITextField alloc]initWithFrame:CGRectMake(60, 120, kBaseWidth-80, 30)];
        _userName.backgroundColor = [UIColor whiteColor];
        _userName.placeholder = self.name;
        _userName.font = [UIFont systemFontOfSize:15];
        _userName.layer.cornerRadius = 5;
        _userName.layer.masksToBounds = YES;
    }
    return _userName;
}

- (UITextField *)password{
    if (!_password) {
        _password = [[UITextField alloc]initWithFrame:CGRectMake(60, 178, kBaseWidth-80, 30)];
        _password.backgroundColor = [UIColor whiteColor];
        _password.placeholder = @"请输入修改的密码6~12位";
        _password.font = [UIFont systemFontOfSize:15];
        _password.layer.cornerRadius = 5;
        _password.layer.masksToBounds = YES;
        _password.secureTextEntry = YES;
        
    }
    return _password;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
